﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Diagnostics;

//Import the EnableWindow method
//[DllImport("user32.dll")]
//[return: MarshalAs(UnmanagedType.Bool)]
//static extern bool EnableWindow(IntPtr hWnd, bool bEnable);.



namespace CCV
{

    public partial class MainForm : Form
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SetParent(IntPtr hWndChild, int hWndNewParent);
        string m_xmlFolder = "";
        string m_rptFile = "";
        string m_title = "";
        int m_hwndParent = 0;
        public int PrintType = 1;

        public MainForm()
        {
          //  ExecuteReport();
         // testLoadReport();
        }



        private void ExecuteReport()
        {
            try
            {
               // if (DateTime.Today > new DateTime(2014, 12, 31))
               //     throw new Exception("Please Contact Administrator");
               // LoadArguments();
                switch (PrintType)
                {
                    case 1:
                        InitializeComponent();
                        Text += "- " + m_title;
                        viewReport();
                        SetParent(this.Handle, m_hwndParent);
                        break;
                    case 2:
                        PrintReport();
                        this.Close();
                        Dispose();
                        break;
                    default:
                        this.Close();
                        break;
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
                this.Close();
            }
        }

        public void PrintReport()
        {
            try
            {
                ReportDocument rptDoc = loadRptDocument();
                rptDoc.PrintToPrinter(1, false, 1, 0);
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
                this.Close();
            }
        }

        private ReportDocument loadRptDocument()
        {
          //  if (DateTime.Today > new DateTime(2014, 12, 31))
           //     throw new Exception("Please Contact Administrator");

            ReportDocument rptDoc = new ReportDocument();
            DataSet dataset = new DataSet();
            foreach (string file in Directory.GetFiles(m_xmlFolder))
            {
                if (Path.GetExtension(file).ToLower() == ".xml")
                    dataset.ReadXml(file);
            }
            rptDoc.Load(m_rptFile);
            Subreports rpts = rptDoc.Subreports;
            if (rpts.Count > 0)
            {
                foreach (ReportDocument subreport in rpts)
                {
                    Tables subtables = subreport.Database.Tables;
                    foreach (Table tbl in subtables)
                    {
                        tbl.SetDataSource(dataset);
                    }
                }
            }

            Tables tables = rptDoc.Database.Tables;
            foreach (Table tbl in tables)
            {
                tbl.SetDataSource(dataset);
            }
            return rptDoc;
        }

        //private void testLoadReport()
        //{
        //    ReportDocument rptDoc = new ReportDocument();
        //    DataSet dataset = new DataSet();

        //    dataset.ReadXml(Application.StartupPath + @"\rpt_attendance_rec_non_staff\xml_form_note.xml");
        //    dataset.ReadXml(Application.StartupPath + @"\rpt_attendance_rec_non_staff\xml_owner.xml");
        //    dataset.ReadXml(Application.StartupPath + @"\rpt_attendance_rec_non_staff\xml_seq_1.xml");
        //    rptDoc.Load(Application.StartupPath + @"\rpt_attendance_rec_non_staff.rpt");
        //   // rptDoc.SetDataSource(dataset);
        //    Tables tables = rptDoc.Database.Tables;
        //    foreach (Table tbl in tables)
        //    {
        //        tbl.SetDataSource(dataset);
        //        tbl.SetDataSource(dataset);
        //        tbl.SetDataSource(dataset);
        //    }
        //    try
        //    {
        //        this.crystalReportViewer1.ReportSource = rptDoc;
        //        //this.crystalReportViewer1.RefreshReport();
        //    }
        //    catch (Exception xx)
        //    {
 
        //    }
        //}

        public void viewReport()
        {
            try
            {
                InitializeComponent();
                ToolStrip tools = (ToolStrip)crystalReportViewer1.Controls[4];
                tools.Items[19].BackgroundImage = null;
                tools.Items[19].Text = "MOOBING PREMIERE CCV";
                tools.Items[19].Font = new Font("Calibri", 8, FontStyle.Bold);
                Text = m_title +" - " + Text;
                SetParent(this.Handle, m_hwndParent);
                ReportDocument rptDoc = loadRptDocument();               
                this.crystalReportViewer1.ReportSource = rptDoc;
                this.crystalReportViewer1.RefreshReport();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
        
        private void fileValidation()
        {
            if (!File.Exists(m_xmlFolder) || !File.Exists(m_xmlFolder))
            {
                ParametersForm frm = new ParametersForm(m_xmlFolder, m_rptFile);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    m_xmlFolder = frm.GetXMLFile();
                    m_rptFile = frm.GetRPTFile();
                }
            }
            // throw new Exception("XML File does not exist");
            //    MessageBox.Show("XML File does not exist");
            //if (File.Exists(rptFile))
            //{
            //    ParametersForm frm = new ParametersForm(xmlFile, rptFile);
            //    frm.ShowDialog();
            //}
            // throw new Exception("Crystal Report File does not exist");
            //  MessageBox.Show("Crystal Report File does not exist");

        }

        public void LoadArguments()
        {
            string[] args = Environment.GetCommandLineArgs();

            string argument = "";
            int index = 0;
            foreach (string arg in args)
            {
                if (index == 0)
                {
                    index++;
                    continue;
                }
                argument += " "+arg;
                index++;
            }
            try
            {
                string[] parameters = argument.Split('|');
              //  if (parameters.Length < 3)
               //     throw new Exception("Please fill the arguments with correct format: rpt_file_with_path|report_title|hwnd_parent");
                m_rptFile = parameters[0].Trim();
                m_xmlFolder = (parameters[0].Substring(0, parameters[0].Length - 4)).Trim();
                m_title = parameters[1];
                m_hwndParent = Convert.ToInt32(parameters[2]);
                PrintType = Convert.ToInt32(parameters[3]);
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message);
             //   this.Close();
            }


            //int xmlFileIndex = -1;
            //int rptFileIndex = -1;
            //int index = 0;
            //foreach (string arg in args)
            //{
            //    if (arg.ToLower() == "-xml")
            //    {
            //        xmlFileIndex = index + 1;
            //    }
            //    else if (arg.ToLower() == "-rpt")
            //    {
            //        rptFileIndex = index + 1;
            //    }
            //    index++;
            //}
            //m_xmlFolder = xmlFileIndex < 0 ? "" : args[xmlFileIndex];
            //m_rptFile = rptFileIndex < 0 ? "" : args[rptFileIndex];
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
          //  if (m_printType == 2)
               // this.Close();
            //try
            //{
            //    if (DateTime.Today > new DateTime(2013, 9, 15))
            //        throw new Exception("Please Contact Administrator");
            //    loadArguments();
            //    fileValidation();
            //    loadReport();
            //}
            //catch (Exception x)
            //{
            //    MessageBox.Show(x.Message);
            //}
        }
    }
}
